import React, { useCallback, useState } from 'react';
import { Button, Modal, Input, Form, Row, Col, message, Upload, Icon } from 'antd';
import { insertFeedback } from '@/services/feedback';
import cookie from 'js-cookie';
import styles from './feedbackmodal.less';

const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 }
};
const EMPTY_FUNC = () => {};

const ModalFormComponent = ({ visible, onCancel, onFinish = EMPTY_FUNC, form }) => {
    const { getFieldDecorator, validateFields, resetFields } = form;
    const [submitting, setSubmitting] = useState(false);
    const [uploadList, setUploadList] = useState([]);

    /* 弹窗关闭，清空数据 */
    const handleClose = useCallback(() => {
        setUploadList([]);
        resetFields();
    }, []);

    const handleSubmit = useCallback(
        e => {
            e.preventDefault();
            validateFields(async (err, values) => {
                if (err) {
                    return;
                }

                try {
                    setSubmitting(true);
                    const { feedbackDesc, feedbackType, feedbackTitle } = values;
                    // const frontTitle = document.title; // 获取网页标题，用于意见反馈标题
                    const frontUrl = window.location.href; // 获取当前地址，用于意见反馈路径
                    const { code, msg } = await insertFeedback({
                        frontTitle: feedbackTitle,
                        bugDesc: feedbackDesc,
                        bugType: feedbackType,
                        screenFiles: uploadList.join(','),
                        frontUrl
                    });
                    if (code === 10000) {
                        message.success('提交成功，感谢您的反馈!');
                    } else {
                        message.error(msg);
                    }
                    onFinish();
                } catch (error) {
                    message.error('提交失败');
                } finally {
                    setSubmitting(false);
                }
            });
        },
        [uploadList]
    );

    const token = cookie.get('Authorization');
    const uploadParam = {
        name: 'file',
        accept: '.jpg,.jpeg,.png,.pdf',
        action: '/api/oa/v1/stream/sysbugreport/uploadfile',
        headers: {
            contentType: 'multipart/form-data',
            Authorization: token
        },
        beforeUpload(file) {
            return new Promise(resolve => {
                const isType =
                    file.type === 'image/jpeg' ||
                    file.type === 'image/jpg' ||
                    file.type === 'image/png' ||
                    file.type === 'application/pdf';
                if (!isType) {
                    message.error('只能上传JPG,JPEG,PNG,PDF格式的文件！');
                }
                const isLimit = file.size / 1024 / 1024 < 1;
                if (!isLimit) {
                    message.error('文件大小不能超过1MB！');
                }
                if (isType && isLimit) {
                    resolve(file);
                }
            });
        },
        onChange(info) {
            if (info.file.status === 'done') {
                setUploadList([...uploadList, info.file.response.data]);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 上传失败`);
            }
        },
        onRemove(file) {
            // 删除文件
            const arr = [...uploadList];
            arr.splice(
                arr.findIndex(item => item === file.response.data),
                1
            );
            setUploadList(arr);
        }
    };

    return (
        <Modal
            visible={visible}
            title="产品建议与反馈"
            footer={null}
            onCancel={onCancel}
            afterClose={handleClose}
            className={styles.wrap}
            maskClosable={false}
            destroyOnClose
        >
            <Form layout="horizontal" onSubmit={handleSubmit} {...layout}>
                <Form.Item label="反馈标题">
                    {getFieldDecorator('feedbackTitle', {
                        rules: [
                            {
                                required: true,
                                message: '请输入反馈标题'
                            },
                            {
                                min: 1,
                                max: 50,
                                message: '请输入1-50字'
                            },
                            { whitespace: true, message: '不能为纯空格' }
                        ]
                    })(<Input placeholder="1-50字" />)}
                </Form.Item>
                <Form.Item label="反馈描述">
                    {getFieldDecorator('feedbackDesc', {
                        rules: [
                            {
                                required: true,
                                message: '请输入内容',
                                type: 'string'
                            },
                            {
                                max: 2500,
                                message: '超出字符长度'
                            },
                            { whitespace: true, message: '不能为纯空格' }
                        ]
                    })(<Input.TextArea rows={6} maxLength={2500} placeholder="请填写您对产品或服务改善的建议" />)}
                </Form.Item>
                <Form.Item className={styles.uploadbox} label=" " colon={false}>
                    <Row gutter={8}>
                        <Col>
                            <Upload {...uploadParam}>
                                <Button disabled={!(uploadList.length < 3)}>
                                    <Icon type="upload" /> 上传文件
                                </Button>
                            </Upload>
                        </Col>
                        <Col className={styles.uptip}>支持jpg、jpeg、png、pdf格式，最大1M</Col>
                    </Row>
                </Form.Item>
                <Row type="flex" justify="end" gutter={8}>
                    <Col>
                        <Button onClick={onCancel}>取消</Button>
                    </Col>
                    <Col>
                        <Button type="primary" htmlType="submit" loading={submitting}>
                            提交
                        </Button>
                    </Col>
                </Row>
            </Form>
        </Modal>
    );
};

const ModalForm = Form.create({ name: 'modal_form' })(ModalFormComponent);

export default ModalForm;
